package com.zwcl.upms.wechat.controller;

import com.alibaba.fastjson.JSONObject;
import com.zwcl.common.core.domain.entity.ApiResult;
import com.zwcl.common.core.exception.BusinessException;
import com.zwcl.common.core.utils.http.RestTemplateHelper;
import com.zwcl.upms.wechat.api.dto.TemplateMsgDto;
import com.zwcl.upms.wechat.entity.Template;
import com.zwcl.upms.wechat.entity.TemplateParam;
import com.zwcl.upms.wechat.api.entity.WxUser;
import com.zwcl.upms.wechat.properties.AuthProperties;
import com.zwcl.upms.wechat.service.WxLoginAuthService;
import com.zwcl.upms.wechat.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 小程序模板消息接口
 */
@Slf4j
@RestController
@RequestMapping("/template")
public class WxTemplateMsgController {

    @Autowired
    private WxLoginAuthService wxLoginAuthService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private AuthProperties authProperties;

    @Autowired
    RestTemplateHelper restTemplateHelper;

    /**
     * 根据code登录，获取保存openId和sessionkey
     * @param dto
     * @return
     */
    @PostMapping(value="/sendMsg")
    public ApiResult sendTemplateMsg(HttpServletRequest request, @Validated @RequestBody TemplateMsgDto dto){
        // 查询用户的openId
        WxUser wxUser = wxUserService.findWxUserByToken(dto.getUserToken());
        if(null == wxUser){
            throw new BusinessException("库中不存在此用户");
        }
        if(!wxUser.getAppType().equals("10")){
            throw new BusinessException("非小程序用户，不能发送订阅消息");
        }
        Template template=new Template();
        template.setTemplate_id(dto.getTemplateId());
        template.setTouser(wxUser.getThirdId());
        template.setPage("pages/index/index");
        //构建模板消息的参数
        List<TemplateParam> params=new ArrayList<TemplateParam>();
        for(Map.Entry<String,String> item : dto.getMsgParam().entrySet()){
            TemplateParam param=new TemplateParam();
            param.setKey(item.getKey());
            param.setValue(item.getValue());
            params.add(param);
        }
        template.setTemplateParamList(params);
        //获取接口调用的token
        String accessToken=wxLoginAuthService.getAccessToken(dto.getAppCode());
        String url=String.format("%s?access_token=%s",authProperties.getTemplateMsgUrl(),accessToken);
        //发送Post请求
        String jsonResult=  restTemplateHelper.postJsonForStr(url,template.toJSON());
        JSONObject result=JSONObject.parseObject(jsonResult);
        if(result!=null){
            int errorCode=result.getInteger("errcode");
            String errorMessage=result.getString("errmsg");
            if(errorCode==0){
                System.out.println("Send Success");
            }else{
                throw new BusinessException("订阅消息发送失败");
            }
        }
        return ApiResult.ok();
    }
}
